/**
 * Copyright (c) 2010-2015 EEFUNG Software Co.Ltd. All rights reserved.
 * 版权所有(c)2010-2015湖南蚁坊软件有限公司。保留所有权利。
 */
package com.milan.analysis.common.extend;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

/**
 * RestClientHttpRequestFactory
 *
 * @author liaozhidan
 * @date 2017/3/12
 */
public class RestClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory{

    private static final Logger LOGGER = LoggerFactory.getLogger(RestClientHttpRequestFactory.class);

    public RestClientHttpRequestFactory(int connectTimeout, int readTimeout, int maxTotalConnectionCount,
                                        int maxConnectionsPerRoute) {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
        PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry);
        connectionManager.setMaxTotal(maxTotalConnectionCount);
        connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
        setHttpClient(new DefaultHttpClient(connectionManager));
        setConnectTimeout(connectTimeout);
        setReadTimeout(readTimeout);
    }

    @Override
    protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
        UriComponentsBuilder componentsBuilder = UriComponentsBuilder.fromUriString(uri.toString());
        MultiValueMap<String, String> queryParams = componentsBuilder.build().getQueryParams();
        for (Map.Entry<String, List<String>> entry : queryParams.entrySet()) {
            String key = entry.getKey();
            List<String> values = entry.getValue();
            if (CollectionUtils.isEmpty(values) || (values.size() == 1 && StringUtils.isBlank(values.get(0)))) {
                componentsBuilder.replaceQueryParam(key);
            } else {
                Object[] queryValues = new Object[values.size()];
                for (int i = 0; i < values.size(); i++) {
                    String value = values.get(i);
                    try {
                        queryValues[i] = URLDecoder.decode(value, CharEncoding.UTF_8);
                    } catch (UnsupportedEncodingException ex) {
                        LOGGER.error("使用 UTF-8 解码查询字符串参数时出现错误！{}\r\n参数名：{}，参数值：{}", new String[] {ex.getMessage(), key,
                            value });
                    }
                }
                componentsBuilder.replaceQueryParam(key, queryValues);
            }
        }
        URI requestUri = componentsBuilder.build().encode().toUri();
        //		if (requestUri.toString().contains("map")) {
        //			System.out.println(requestUri);
        //		}
        return super.createHttpUriRequest(httpMethod, requestUri);
    }

}
